#!/usr/bin/env bash
set -e

for f in packages/*; do
	if [[ -f ${f}/package.yaml ]]; then
		if [[ -n $(cat ${f}/package.yaml | yq r - imageMirror) ]]; then
			for (( i=0; i<$(cat ${f}/package.yaml | yq r - imageMirror --length); i++ )); do
				name=$(cat ${f}/package.yaml | yq r - imageMirror.[$i].name)
				for (( j=0; j<$(cat ${f}/package.yaml | yq r - imageMirror.[$i].images --length); j++ )); do
					arch=$(cat ${f}/package.yaml | yq r - imageMirror.[$i].images.[$j].arch)
					os=$(cat ${f}/package.yaml | yq r - imageMirror.[$i].images.[$j].os)
					original=$(cat ${f}/package.yaml | yq r - imageMirror.[$i].images.[$j].original)
					tag=$(cat ${f}/package.yaml | yq r - imageMirror.[$i].images.[$j].tag)
					docker pull $original:$tag
					docker tag $original:$tag $name-$arch:$tag
					docker push $name-$arch:$tag
					docker manifest create --amend $name:$tag $name-$arch:$tag
					docker manifest annotate $name:$tag $name-$arch:$tag --arch $arch --os $os
				done
				docker manifest push -p $name:$tag
			done
		fi
  fi
done